package com.technology.education.ui.common.pay

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.technology.education.databinding.ActivityPayBinding
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity
import com.alipay.sdk.app.PayTask
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.PayBodyModel
import com.technology.education.data.model.WXPayBodyModel
import com.technology.education.data.model.WxPayBody
import com.technology.education.ext.getAppViewModel
import com.technology.education.ext.postEventBus
import com.technology.education.ext.toast
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory


/**
 *@author:create by BZY
 *Date: 2022/3/23 08
 */
class PayActivity : BaseVmDbActivity<PayViewModel, ActivityPayBinding>() {
    var money: String? = null
    override fun initView(savedInstanceState: Bundle?) {
        intent.apply {
            mViewModel.orderId = getStringExtra("orderId") ?: ""
            money = getStringExtra("money")
            mViewModel.orderType = getIntExtra("type", 0)
            if (!money.isNullOrEmpty()) {
                mViewModel.payString.set("立即支付 ¥$money")
            }
        }
        mDatabind.vm = mViewModel
        mDatabind.toolbar.tvTitle.text = "支付"
        mDatabind.toolbar.toolbar.apply {
            setNavigationOnClickListener {
                onBackPressed()
            }
        }
        initWx()
    }

    var wxApi: IWXAPI? = null
    private fun initWx() {
        wxApi = WXAPIFactory.createWXAPI(this, AppData.WX_ID)
        wxApi?.registerApp(AppData.WX_ID)
    }

    override fun showLoading(message: String) {

    }

    override fun dismissLoading() {

    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            if (mViewModel.payType.get() == 1) {
                if (it is PayBodyModel) {
                    aliPay(it.body)
                }

            } else {
                if (it is WXPayBodyModel){
                    wxPay(it.body)
                }

            }
        }

        getAppViewModel().wechatPayResult.observe(this) {
            if (it) {
                paySuccess()
            }
        }
    }

    private fun wxPay(body: WxPayBody) {
        wxApi?.sendReq(PayReq().apply {
            appId = body.appid
            partnerId = body.partnerid
            prepayId = body.prepayid
            packageValue = "Sign=WXPay"
            nonceStr = body.noncestr
            timeStamp = body.timestamp
            sign = body.sign
        })
    }

    private val SDK_PAY_FLAG = 333
    private fun aliPay(info: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result = alipay.payV2(info, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    private val mHandler: Handler = Handler(
        Looper.getMainLooper()
    ) {
        if (it.what == SDK_PAY_FLAG) {
            val result = it.obj as Map<String, String>
            when {
                result["resultStatus"] == "9000" -> {
                    paySuccess()
                    toast("支付成功")
                }
                result["resultStatus"] == "4000" -> {
                    toast("订单支付失败")
                }
                result["resultStatus"] == "6001" -> {
                    toast("订单支付已取消")
                }
                else -> {
                    toast("支付发生错误")
                }
            }
        }
        true
    }

    /**
     * 支付成功之后将事件分发,同时结束页面
     */
    private fun paySuccess() {
        if (mViewModel.orderType == SpKeys.PAY_TYPE_DEPOSIT) {
            getAppViewModel().getInfo(onlyData = true)
        }
        postEventBus(SpKeys.PAY_RESULT_SUCCESS, mViewModel.orderId)
        onBackPressed()
    }
}